<template>
	<view>
		<TopSearch v-model:value="searchValue" @onGetSearchData="onSearch" />
		<VipList />
		<SearchList :data="cookbookData.rows" />
	</view>
</template>

<script setup>
	import VipList from '../../components/vip-list/vip-list.vue';
	import TopSearch from '../../components/top-search/top-search.vue';
	import SearchList from '../../components/search-list/search-list.vue';

	import { onLoad, onReachBottom } from '@dcloudio/uni-app';
	import { reactive, ref } from 'vue';
	import { getSearchCookbookApi } from '../../../api/cookbook';

	const searchValue = ref('');
	const pageData = ref({ currentPage: 1, pageSize: 20 });
	const cookbookData = reactive({ rows: [], total: 0 })

	onLoad((options) => {
		if (options.name) {
			searchValue.value = options.name;
		}
		onGetSearchData();
	})

	// 页面滑动到底部时触发
	onReachBottom(() => {
		if (cookbookData.rows.length >= cookbookData.total) {
			uni.showToast({
				title: '没有更多了',
				icon: 'none',
				duration: 2000
			});
		} else {
			pageData.value.currentPage++;
			onGetSearchData();
		}
	})


	const onSearch = () => {
		pageData.value.currentPage = 1;
		cookbookData.rows = [];
		cookbookData.total = 0;
		onGetSearchData();
	}

	function onGetSearchData() {
		getSearchCookbookApi({
			value: searchValue.value,
			...pageData.value
		}).then(res => {
			if (res.code == 200) {
				cookbookData.rows = [
					...cookbookData.rows, // 保留旧数据
					...res.data.rows
				];
				cookbookData.total = res.data.total;
			}
		})
	}
</script>

<style>

</style>